package qs.openxt.libs.remoting;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import android.os.AsyncTask;

public class BusinessTask extends AsyncTask<JSONObject, Integer, JSONObject> {
	private Remoting callBack = null;
	private Client client = null;

	public BusinessTask(Remoting callBack) {
		this.callBack = callBack;
	}

	public boolean cancelTask() {
		if (cancel(true)) {
			this.callBack = null;
			client.close();
			return true;
		}
		return false;
	}

	protected JSONObject doInBackground(JSONObject... params) {
		try {
			JSONObject packet = params[0];
			client = (Client) packet.get("client");
			if (packet != null && client != null) {
				String result = null;
				JSONObject args = packet.getJSONObject("args");
				if(args != null) {
					Object data = args.get("data");
					if (data instanceof JSONObject) {
						Map<String, String> param = new HashMap<String, String>();
						JSONObject $data = (JSONObject) data;
						Iterator it = $data.keySet().iterator();
						while (it.hasNext()) {
							String key = (String) it.next();
							param.put(key, $data.getString(key));
						}
						result = client.request(param);
					} else
						result = client.request(data);
				}else
					result = client.request(null);

				if (result == null)
					throw new Exception("返回数据错误");

				JSONObject json = new JSONObject();
				json.put("status", Client.STATUS_OK);
				json.put("value", result);
				return json;
			}
		} catch (Exception e) {
			try {
				JSONObject json = new JSONObject();
				json.put("status", Client.STATUS_ERR);
				if(e instanceof SocketTimeoutException)
					json.put(Client.ERR_MESSAGE, "连接超时，请重试");
				else
					json.put(Client.ERR_MESSAGE, e.getMessage());
				return json;
			} catch (Exception e0) {
			}
		}
		
		JSONObject json = new JSONObject();
		try {
			json.put("status", Client.STATUS_ERR);
			json.put("message", "尚不支持该服务");
		} catch (Exception e0) {
		}
		return json;
	}

	protected void onPostExecute(JSONObject result) {
		super.onPostExecute(result);
		if (!Client.STATUS_OK.equals(result.getString("status")) && this.callBack != null)
			this.callBack.onError(result.getString("message"));
		else if (this.callBack != null)
			this.callBack.onSuccess(result.getString("value"));
	}
}